package com.heima.wemedia.service.iml;

import com.alibaba.fastjson.JSONArray;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.exception.CustException;
import com.heima.feigins.AdminFeign;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    WmNewsMapper wmNewsMapper;

    @Value("${file.oss.web-site}")
    String webSite;
    @Autowired
    RabbitTemplate rabbitTemplate;
    /*
    * 文章自动审核，
    * */
    @Override
    public void autoScanWmNews(Integer id) {
        //1.校验参数
        if (id ==null){
            log.error("自动审核文章失败    文章id为空");
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"参数不能为空");
        }
        //1.1根据id查询文章信息
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null){
            log.error("自动审核文章失败    文章不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"根据id查询文章的信息不存在");
        }
        //1.2文章状态是否为提交待审核，不是待审核直接终止该方法
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_SUMMIT_STATUS)){
            log.error("自动审核文章失败    文章状态不为1");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"该文章不是处于提交待审核状态");
        }
        //2.审核文章信息
        //查询文章内容信息中所有文本内容和图片信息
         Map<String,Object> textAndImge = takeTextAndImage(wmNews);
          //2.1对文章进行自定义敏感词审核，DFA算法
        String content = (String) textAndImge.get("content");
       boolean result = checkContextBySensitive(content,wmNews);
       if (!result){
          return;
       }
       log.info("敏感词审核正常，没出现敏感词");
        //2。2对文章文本内容进行文本反垃圾审核
      boolean result1 =  checkContextByAliYun(content,wmNews);
      if (!result1){
          return;
      }
        log.info("阿里云文本审核正常，没出现违规内容");
        //2.3对文章图片进行阿里云图片审核
        List<String> images = (List<String>) textAndImge.get("images");
        boolean result2 = checkImageByAliYun(images,wmNews);
        if (!result2){
            return;
        }
        log.info("阿里云图片审核正常，没出现违规内容");
        //文章审核成功
        wmNews.setStatus((short) 8);
        wmNews.setReason("审核通过");
        wmNewsMapper.updateById(wmNews);
        //TODO 定时发布任务
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );

    }

    @Autowired
    GreenImageScan greenImageScan;
   //阿里云图片审核
    private boolean checkImageByAliYun(List<String> images, WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greenImageScan.imageUrlScan(images);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    log.info("阿里云图片审核不通过");
                    wmNews.setStatus((short) 2);
                    wmNews.setReason("阿里云图片审核出现违规内容");
                    wmNewsMapper.updateById(wmNews);
                    flag = false;
                    break;
                case "review":
                    log.info("阿里云图片审核不确定，有擦边球行为");
                    wmNews.setStatus((short) 3);
                    wmNews.setReason("阿里云图片审核出现异常转为人工处理");
                    wmNewsMapper.updateById(wmNews);
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("阿里云图片审核出现异常，转为人工处理，失败原因：" + e.getMessage());
            //阿里云图片审核异常，修改文章状态转为人工处理
            wmNews.setStatus((short) 3);
            wmNews.setReason("阿里云图片审核出现异常转为人工处理");
            wmNewsMapper.updateById(wmNews);
            flag = false;
        }
        return flag;
    }

        @Autowired
    GreenTextScan greenTextScan;
    //阿里云文本反垃圾检测
    private boolean checkContextByAliYun(String content, WmNews wmNews)  {
        boolean flag = true;
        try {
            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion){
                case "block":
                    log.info("阿里云文本审核不通过");
                    wmNews.setStatus((short) 2);
                    wmNews.setReason("阿里云文本审核出现违规内容");
                    wmNewsMapper.updateById(wmNews);
                    flag=false;
                    break;
                case "review":
                    log.info("阿里云文本审核不确定，有擦边球行为");
                    wmNews.setStatus((short) 3);
                    wmNews.setReason("阿里云文本审核出现异常转为人工处理");
                    wmNewsMapper.updateById(wmNews);
                    flag=false;
                    break;

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("阿里云文本审核出现异常，异常原因    "+e.getMessage());
            //阿里云文本审核异常，修改文章状态转为人工处理
            wmNews.setStatus((short) 3);
            wmNews.setReason("阿里云文本审核出现异常转为人工处理");
            wmNewsMapper.updateById(wmNews);
            flag=false;
        }
        return flag;
    }

    @Autowired
    AdminFeign adminFeign;
    //敏感词，自定义敏感词列表检查
    private boolean checkContextBySensitive(String content, WmNews wmNews) {
        //查询出自定义的所有敏感词
        ResponseResult<List<String>> allSensitive = adminFeign.selectAllSensitive();
        //判断调用有没有成功
        if (allSensitive.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用出错");
        }
        List<String> sensitiveData = allSensitive.getData();
        //初始化敏感词列表
        SensitiveWordUtil.initMap(sensitiveData);
        Map<String, Integer> matchWords = SensitiveWordUtil.matchWords(content);
        boolean flag=true;
        if (matchWords != null && matchWords.size()>0){
            //有敏感词将文章状态设为不通过,审核失败状态码为2,设置文章不用过理由
            wmNews.setStatus((short) 2);
            wmNews.setReason("文章内容包含敏感词："+matchWords);
            wmNewsMapper.updateById(wmNews);
            flag=false;
        }
        return flag;
    }


    private Map<String, Object> takeTextAndImage(WmNews wmNews) {
        String content = wmNews.getContent();
        if (StringUtils.isBlank(content)){
            log.error("自动审核文章失败    文章内容为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章内容为空");
        }
        //将字符串转化为map集合
        List<Map> mapList = JSONArray.parseArray(content, Map.class);
        //抽取本文内容
        String collect = mapList.stream().filter(o -> o.get("type").equals("text")).map(map -> (String) map.get("value"))
                .collect(Collectors.joining("_hmtt_"));
       //文本内容和标题拼接在一起，方便一次性判断不用分开判断
        collect=collect+"_hmtt_"+wmNews.getTitle();

        //抽取图片内容,封面图片是没有前缀的
        List<String> imageList = mapList.stream().filter(o -> o.get("type").equals("image")).map(map -> (String) map.get("value"))
                .collect(Collectors.toList());
        String images = wmNews.getImages();
        if (StringUtils.isNotBlank(images)){
            String[] imageArray = images.split(",");
            List<String> collect1 = Arrays.stream(imageArray).map(url -> webSite + url).collect(Collectors.toList());
            imageList.addAll(collect1);
        }
        //统一去重
        imageList=imageList.stream().distinct().collect(Collectors.toList());
        Map<String,Object> maps=new HashMap<>();
        maps.put("content",collect);
        maps.put("images",imageList);
        return maps;
    }
}
